package repository

import (
	"fmt"
	"gluenet/modules/manager/server/adapter/repository/mysql"
	"gluenet/modules/manager/server/domain/dependency"
	"gluenet/modules/manager/server/domain/entity"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
)

func init() {
	prepare.RegisterRepo(func() {
		repo := NewAreaRepo()
		prepare.InjectDependency(func() dependency.AreaRepo {
			return repo
		})
	})
}

type Area struct {
}

func (a *Area) Get(AreaID string) (*entity.Area, error) {
	var obj []entity.Area
	if err := mysql.DB.Where(map[string]interface{}{
		"area_id": AreaID,
	}).Find(&obj); err != nil {
		return nil, err
	}

	//fmt.Printf("%v %v", len(obj), obj)

	if len(obj) > 1 {
		return nil, fmt.Errorf("much primary keys in sql")
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}

	return &obj[0], nil
}

func (a *Area) FindBy(m map[string]interface{}) ([]entity.Area, error) {
	var obj []entity.Area
	if err := mysql.DB.Where(m).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}

	return obj, nil
}

func NewAreaRepo() *Area {
	r := &Area{}
	return r
}
